<template>
	<div>
		<div id="this.instance-conf-trans-wrapper" class="component-configuation-transformer">
			<div>
				<div class="head-configuation">
					<div class="head-left-configuation">
						<div>{{ state.name }}</div>
						<div style="margin-left: 0.5rem; font-style: italic">{{ state.version }}</div>
						<!-- <img :src="instance.icon" class="model-img" /> -->
						<!-- <img :src="instance.theme.border" class="model-img" /> -->
					</div>
					<!-- <el-button
						size="small"
						class="head-right-configuation"
						type="primary"
						@click="clickAddIconButton">
						选择图片
					</el-button> -->
				</div>
				<el-divider></el-divider>
				<div class="position-input">
					<div>位置尺寸</div>
					<div :class="isDragging ? 'dragging' : ''" @click="toggleDragMode">
						<el-icon>
							<Lock v-if="isDragging === false" />
							<Unlock v-else />
						</el-icon>
					</div>
					<div>
						<el-select size="small" v-model="state.positionType">
							<el-option
								v-for="p in state.positionEnum"
								:key="p.value"
								:label="p.key"
								:value="p.value"></el-option>
						</el-select>
					</div>
				</div>
				<div class="pos-value" v-if="state.positionType == 0">
					<div class="line-title">T</div>
					<el-input-number
						size="small"
						class="line-input-num"
						controls-position="right"
						v-model="state.top"></el-input-number>
					<div class="line-title">L</div>
					<el-input-number
						size="small"
						class="line-input-num"
						controls-position="right"
						v-model="state.left"></el-input-number>
				</div>
				<div class="pos-value" v-if="state.positionType == 1">
					<div class="line-title">T</div>
					<el-input-number
						size="small"
						class="line-input-num"
						controls-position="right"
						v-model="state.top"></el-input-number>
					<div class="line-title">R</div>
					<el-input-number
						size="small"
						class="line-input-num"
						controls-position="right"
						v-model="state.right"></el-input-number>
				</div>
				<div class="pos-value" v-if="state.positionType == 2">
					<div class="line-title">L</div>
					<el-input-number
						size="small"
						class="line-input-num"
						controls-position="right"
						v-model="state.left"></el-input-number>
					<div class="line-title">B</div>
					<el-input-number
						size="small"
						class="line-input-num"
						controls-position="right"
						v-model="state.bottom"
						v-if="state.positionType == 2 || state.positionType == 3"></el-input-number>
				</div>
				<div class="pos-value" v-if="state.positionType == 3">
					<div class="line-title">B</div>
					<el-input-number
						size="small"
						class="line-input-num"
						controls-position="right"
						v-model="state.bottom"
						v-if="state.positionType == 2 || state.positionType == 3"></el-input-number>
					<div class="line-title">R</div>
					<el-input-number
						size="small"
						class="line-input-num"
						controls-position="right"
						v-model="state.right"></el-input-number>
				</div>
				<div class="pos-value">
					<div class="line-title">W</div>
					<el-input-number
						size="small"
						class="line-input-num"
						controls-position="right"
						v-model="state.width"></el-input-number>
					<div class="line-title">H</div>
					<el-input-number
						size="small"
						class="line-input-num"
						controls-position="right"
						v-model="state.height"></el-input-number>
				</div>
				<el-divider></el-divider>
			</div>
			<!-- {{ state.clonedConfiguration.length }} -->
			<!-- {{
				state.clonedConfiguration[2].type.replace(/( |^)[a-z]/, (L: any) => `My${L.toUpperCase()}`)
			}} -->
			<!-- {{ state.clonedConfiguration[0] }} -->
			<div v-for="(config, index) in state.clonedConfiguration" :key="config.type + index">
				<component
					v-if="configShow"
					:is="comMaps[getCpntName(config.type)]"
					v-model:data="state.clonedConfiguration[index]"
					:ref="config.type + index"
					@handleValueChange="handleValueChange" />
			</div>
		</div>
		<div class="down-btn-area">
			<el-button size="small" style="margin: 10px" type="primary" @click="handleValueChange">
				保存基础配置
			</el-button>
		</div>
		<el-dialog
			v-model="state.dialogVisible"
			class="icon-dialog"
			title="上传图片"
			:fullscreen="false">
			<button
				type="button"
				aria-label="Close"
				class="el-dialog__headerbtn"
				@click="handleDialogCloseBtn">
				<el-icon><CloseBold /></el-icon>
			</button>
			<el-tabs v-model="activeName">
				<el-tab-pane label="组件图标" name="icon">
					<el-button type="primary">
						<el-icon><UploadFilled /></el-icon>
						点击上传
					</el-button>
					<input
						id="uploadIcon"
						class="uploadIcon"
						type="file"
						ref="icon"
						@change="uploadIconFile"
						accept="image/x-png, image/jpg, image/jpeg" />
					<div class="image-list">
						<div
							class="image"
							v-for="(item, index) in state.iconList"
							:key="index"
							@click="handleIconChoose(item)">
							<img :src="item" />
						</div>
					</div>
				</el-tab-pane>
				<el-tab-pane label="组件边框" name="img">
					<el-button type="primary">
						<el-icon><UploadFilled /></el-icon>
						点击上传
					</el-button>
					<input
						id="uploadBorder"
						class="uploadIcon"
						type="file"
						ref="border"
						@change="uploadBorderFile"
						accept="image/x-png, image/jpg, image/jpeg" />
					<div class="image-list">
						<div
							class="image"
							v-for="(item, index) in state.imageBorderList"
							:key="index"
							@click="handleBorderChoose(item)">
							<img :src="item" />
						</div>
					</div>
				</el-tab-pane>
			</el-tabs>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, toRefs, ref, watch, computed, provide } from 'vue';
import {
	MyInput,
	MySelect,
	MyBoolean,
	MyTextBox,
	MyImageBox,
	MyCallback,
	MyArray,
	MyNumber,
	MyRadio,
	MyCheckbox,
	MyRange,
	MyModel,
	MyColor
} from './Component/index.js';
import _ from 'lodash';
import * as CIF_API from '@CIF/API/api.js';
import { ElMessage } from 'element-plus';
import { reduceConfig, increaseConfig } from '@CIF/Utils/reduce-config';
import { usePrimaryStore } from '@/store';

const comMaps: any = {
	MySelect,
	MyInput,
	MyBoolean,
	MyTextBox,
	MyImageBox,
	MyCallback,
	MyArray,
	MyNumber,
	MyCheckbox,
	MyRadio,
	MyRange,
	MyModel,
	MyColor
};
const emit = defineEmits(['setConfiguredDataToInstance']);
const store = usePrimaryStore();
const props = defineProps({
	instance: {
		type: Object,
		default() {
			return {};
		}
	}, // cpntTreeNode
	id: String,
	setConfiguredDataToInstance: {
		type: Function,
		default() {
			return () => {};
		}
	}
});

const state: any = reactive({
	positionEnum: [
		{ key: 'L-T', value: 0 },
		{ key: 'R-T', value: 1 },
		{ key: 'L-B', value: 2 },
		{ key: 'R-B', value: 3 }
	],
	// 组件定位类型，确定组件到底基于左上、右上、左下还是右下
	// 枚举：0（左上）、1（右上）、2（左下）、3（右下）
	positionType: 0,
	top: 0,
	right: 0,
	bottom: 0,
	left: 0,
	width: 0,
	height: 0,
	clonedConfiguration: [], // instance的configuration
	configData: {},

	// 上传图标弹窗
	dialogVisible: false,
	iconList: [],
	imageBorderList: []
});
const activeName = ref('icon');

const isDragging = computed(() => {
	return store.getDragMode;
});
const containerHeight = computed(() => {
	return store.getContainerSize.height;
});
const containerWidth = computed(() => {
	return store.getContainerSize.width;
});

let instance = reactive(props.instance);
function initConfiguration(instance: any) {
	state.clonedConfiguration = _.cloneDeep(_.get(instance, 'definitionRefrence.configuration'));
	// console.log('1111clonedConfiguration', state.clonedConfiguration);
	state.positionType = _.get(instance, 'positionType');
	// 定位类型，0：左上角，1：右上角，2：左下角，3：右下角
	// switch(`${this.positionType}`) {
	//   case '0':
	//     this.top = _.get(instance, 'top')
	//     this.left = _.get(instance, 'left')
	//     break
	//   case '1':
	//     this.top = _.get(instance, 'top')
	//     this.right = _.get(instance, 'right')
	//     break
	//   case '2':
	//     this.bottom = _.get(instance, 'bottom')
	//     this.left = _.get(instance, 'left')
	//     break
	//   case '3':
	//     this.bottom = _.get(instance, 'bottom')
	//     this.right = _.get(instance, 'right')
	//     break
	// }
	state.top = _.get(instance, 'top');
	state.right = _.get(instance, 'right');
	state.bottom = _.get(instance, 'bottom');
	state.left = _.get(instance, 'left');
	state.width = _.get(instance, 'width');
	state.height = _.get(instance, 'height');
	state.configData = _.get(instance, 'configData');
	state.icon = _.get(instance, 'definitionRefrence.icon');
	state.name = _.get(instance, 'definitionRefrence.name');
	state.version = _.get(instance, 'definitionRefrence.version');
	increaseConfig(state.configData, state.clonedConfiguration);
}
function initConfiguration1(instance: any) {
	state.top = _.get(instance, 'top');
	state.right = _.get(instance, 'right');
	state.bottom = _.get(instance, 'bottom');
	state.left = _.get(instance, 'left');
	state.width = _.get(instance, 'width');
	state.height = _.get(instance, 'height');
	state.icon = _.get(instance, 'definitionRefrence.icon');
	state.name = _.get(instance, 'definitionRefrence.name');
}
initConfiguration(instance);
const configShow = ref(true);
watch(
	() => props.instance.uuid,
	() => {
		instance = props.instance;
		// configShow.value = false;
		// setTimeout(() => {
		// 	configShow.value = true;
		// }, 0);
		initConfiguration(props.instance);
	}
);
watch(
	() => props.instance,
	(newVal) => {
		instance = newVal;
		initConfiguration1(newVal);
	},
	{ deep: true }
);
watch(
	() => state.positionType,
	(newVal, oldVal) => {
		if (newVal === oldVal) return;
		instance.positionType = newVal;
	}
);
watch(
	() => state.top,
	(newVal, oldVal) => {
		if (newVal === oldVal) return;
		instance.top = newVal;
	}
);
watch(
	() => state.right,
	(newVal, oldVal) => {
		if (newVal === oldVal) return;
		instance.right = newVal;
	}
);
watch(
	() => state.bottom,
	(newVal, oldVal) => {
		if (newVal === oldVal) return;
		instance.bottom = newVal;
	}
);
watch(
	() => state.left,
	(newVal, oldVal) => {
		if (newVal === oldVal) return;
		instance.left = newVal;
	}
);
watch(
	() => state.width,
	(newVal, oldVal) => {
		if (newVal === oldVal) return;
		instance.width = newVal;
	}
);
watch(
	() => state.height,
	(newVal, oldVal) => {
		if (newVal === oldVal) return;
		instance.height = newVal;
	}
);
watch(
	() => state.clonedConfiguration,
	(newVal) => {
		console.log('clonedConfiguration', newVal);
	},
	{ deep: true }
);
watch(
	() => state.configData,
	(newVal) => {
		const tmp = _.cloneDeep(state.clonedConfiguration);
		try {
			increaseConfig(newVal, tmp);
		} catch (e) {
			if (_.get(window, 'cif.config.logger.enable', false) === true) {
				console.log('CIF.CC.ComponentConfiguationTransformer:watch configData', tmp, e);
			}
		}
		state.clonedConfiguration = tmp;
	},
	{ deep: true }
);

function getCpntName(name: string) {
	return name.replace(/( |^)[a-z]/, (L: any) => `My${L.toUpperCase()}`);
}

// 点击打开图片上传窗体
function clickAddIconButton() {
	CIF_API.getIconList().then((res: any) => {
		if (res.status) {
			state.iconList = res.data;
		}
	});
	CIF_API.getImageBorderList().then((res: any) => {
		if (res.status) {
			state.imageBorderList = res.data;
		}
	});
	state.dialogVisible = true;
}

function toggleDragMode() {
	store.toggleDragMode();
}

function handleDialogCloseBtn() {
	state.dialogVisible = false;
}
function getQueryVariable(variable) {
	const query = window.location.search.substring(1);
	const vars = query.split('&');
	for (let i = 0; i < vars.length; i++) {
		const pair = vars[i].split('=');
		if (pair[0] == variable) {
			return pair[1];
		}
	}
	return 'test';
}
// 上传图标文件
const icon = ref();
function uploadIconFile() {
	let file = icon.value.files[0];
	let formData = new FormData();
	formData.append('file', file);
	formData.append('tenantId', getQueryVariable('tenantId'));
	// this.dialogLoading = true;
	CIF_API.uploadIcon(formData).then((res: any) => {
		if (res.status) {
			ElMessage.success('上传图标成功');
			CIF_API.getIconList().then((res: any) => {
				if (res.status) {
					state.iconList = res.data;
				}
				// this.dialogLoading = false;
			});
		}
	});
}

// 更新组件icon信息
function handleIconChoose(icon: any) {
	if (_.get(window, 'cif.config.logger.enable', false) === true) {
		console.log(
			'CIF.ComponentConfiguationTransformer:handleIconChoose 将修改后的组件ICON至组件实例'
		);
	}
	instance.icon = icon;
	store.setSelectedInstance(instance);
	state.dialogVisible = false;
}

//上传边框文件
const border = ref();
function uploadBorderFile() {
	let file = border.value.files[0];
	let formData = new FormData();
	formData.append('file', file);
	formData.append('tenantId', getQueryVariable('tenantId'));
	// state.dialogLoading = true;
	CIF_API.uploadImageBorder(formData).then((res: any) => {
		if (res.status) {
			ElMessage.success('上传边框成功');
			CIF_API.getImageBorderList().then((res: any) => {
				if (res.status) {
					state.imageBorderList = res.data;
				}
				// state.dialogLoading = false;
			});
		}
	});
}

// 更新组件border信息
function handleBorderChoose(border: any) {
	if (_.get(window, 'cif.config.logger.enable', false) === true) {
		console.log(
			'CIF.ComponentConfiguationTransformer:handleBorderChoose 将修改后的组件Border至组件实例'
		);
	}
	instance.theme.border = border;
	store.setSelectedInstance(instance);
	state.dialogVisible = false;
}

function mergeConfigData() {
	const ret = {
		configData: reduceConfig(state.clonedConfiguration),
		positionType: state.positionType,
		top: state.top,
		right: state.right,
		bottom: state.bottom,
		left: state.left,
		width: state.width,
		height: state.height
	};
	// if (_.get(window, 'cif.config.logger.enable', false) === true) {
	// 	console.log(
	// 		'CIF.CC.ComponentConfiguationTransformer:mergeConfigData',
	// 		ret,
	// 		state.clonedConfiguration
	// 	);
	// }
	return ret;
}

function handleValueChange() {
	if (_.get(window, 'cif.config.logger.enable', false) === true) {
		console.log('CIF.CC.ComponentConfiguationTransformer:handleValueChange 检测到值变动');
		console.log('-111111111111clonedConfiguration:', state.clonedConfiguration);
	}
	// 将组件config信息保存起来
	emit('setConfiguredDataToInstance', props.id, mergeConfigData());
	// props.setConfiguredDataToInstance(props.id, mergeConfigData());
}

onMounted(() => {});
defineExpose({ ...toRefs(state) });
provide('configuration', state.clonedConfiguration);
</script>

<style lang="scss" scoped>
.component-configuation-transformer {
	padding: 15px 15px 0 15px;
	height: calc(100% - 72px);
	overflow-y: auto;
	// 滚动条样式
	&:hover::-webkit-scrollbar {
		background: #3d3f46; /* 滑块颜色 */
	}
	&::-webkit-scrollbar {
		/* 滚动条默认隐藏 */
		background-color: transparent;
		width: 6px; /* 滚动条宽度 */
	}
	&::-webkit-scrollbar-track {
		/* 滚动条轨道样式 */
		background: transparent;
	}

	&::-webkit-scrollbar-thumb {
		/* 滚动条滑块样式 */
		// background: #3d3f46; /* 滑块颜色 */
		border-radius: 3px; /* 滑块圆角 */
	}

	&::-webkit-scrollbar-thumb:hover {
		/* 鼠标悬停在滑块上时样式 */
		background: #55575e; /* 滑块悬停颜色 */
	}

	.position-input {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin: 10px 0;

		div:nth-child(1) {
			width: 4rem;
		}
		div:nth-child(2) {
			width: 20px;
			cursor: pointer;
			i {
				font-size: 20px;

				&:hover {
					background-color: rgba(90, 93, 94, 0.61);
				}
			}
		}
		div:nth-child(3) {
			flex: 1;
			text-align: right;

			& > div {
				width: 118px;
				margin: 0 !important;
			}
		}

		.dragging {
			i {
				background-color: var(--primary-high);
			}
		}
	}

	.pos-value {
		display: grid;
		grid-template-columns: 1fr 4fr 1fr 4fr;
		grid-template-rows: 28px;
		grid-column-gap: 10px;
		grid-row-gap: 10px;
		justify-content: space-evenly;
		align-content: center;
		justify-items: center;
		align-items: center;
		margin: 10px 0;
		border: none;

		.line-input-num {
			width: auto;
		}

		/* .line {
      display: flex;
      margin-bottom: 10px;
      .title {
        width: 73px;
        overflow: hidden;
        line-height: 40px;
        white-space: nowrap;
        text-align: right;
        vertical-align: middle;
        margin-right: 10px;
      }
      .input {
        flex: 1;
      }
      .input-num {
        width: 100%;
      }
    } */
	}

	.head-configuation {
		display: flex;
		justify-content: space-between;

		.head-left-configuation {
			display: flex;
			width: 50%;
			margin-top: 8px;

			.model-img {
				width: 20px;
				height: 20px;
				margin-left: 10px;
			}
		}
	}
}
.down-btn-area {
	position: relative;
	width: 100%;
	bottom: 0;
	right: 0;
	background-color: transparent;
	border-top: 1px solid var(--primary-high);
}

::v-deep .el-divider--horizontal {
	margin: 12px 0;
}

:deep(.icon-dialog) {
	// margin-top: 15vh;
	// width: 80%;
	.el-dialog__headerbtn {
		z-index: 100;
		padding: 0;
	}
	.el-dialog__header {
		display: none;
	}
	.el-dialog__body {
		padding: 24px 25px;
		overflow: hidden;
	}
	.el-tabs__content {
		max-height: calc(75vh - 177px);
		overflow-y: auto;
	}
	.uploadIcon {
		position: absolute;
		left: 32px;
		width: 110px;
		height: 37px;
		opacity: 0;
		cursor: pointer;
	}

	.image-list {
		display: flex;
		flex-wrap: wrap;
		margin-top: 20px;

		.image {
			width: 3rem;
			height: 3rem;
			margin: 20px 10px;
			padding: 5px;
			box-shadow: 0px 0px 10px 1px rgba(0, 17, 52, 0.14);
			border-radius: 4px;
			border: 1px solid #ebeef5;
			/* transition: all 0.2s cubic-bezier(0.18, 0.89, 0.32, 1.28); */
			transition:
				box-shadow 0.25s cubic-bezier(0, 0.42, 0.2, 0.99) 0s,
				transform 0.1s cubic-bezier(0, 0.42, 0.2, 0.99) 0s;
			cursor: pointer;

			img {
				width: 100%;
				height: 100%;
			}
		}

		.image:hover {
			transform: scale(1.2);
			box-shadow: 0px 0px 10px 3px rgba(117, 156, 233, 0.9);
		}
	}
}
</style>
